package com.bodgittandscarper.broker;

import com.bodgittandscarper.broker.server.Server;
import com.bodgittandscarper.broker.types.ModeFlag;
import com.bodgittandscarper.brokerhmi.BrokerHMI;

/**
 * Start class and main entrance for the BodgittAndScarper Application. Contains the static void <code>main</code> method.
 * <p>
 * The Application can be started in 3 different modes - Server, Alone and Client. The mode is defined with startup parameters
 * in the <code>main</code> method. The mode cannot be changed during runtime.
 * 
 * 
 * @author Morten Rummelhoff
 *
 */
public class Start {
	
	/**
	 * Constructor specifying which mode the application is started in.
	 * 
	 * @param modeFlag Mode of the application. 
	 */
	public Start(ModeFlag modeFlag) {
		
		Server server = null;
		
		switch (modeFlag) {	
		
		case SERVER:
			//Setup Database access
			server = new Server(modeFlag);
			break;
		case ALONE: //fall through
			//Setup Database access
			server = new Server(modeFlag);
		case CLIENT:
			new BrokerHMI(modeFlag, server);
			break;
		
		}
	}
	
	private static void showHelp(String errorArg) {
		System.out.printf("Invalid argument: " +  errorArg + ". Only following argument are valid: ");
		
		System.out.printf("\n\n\t server. This starts the BodgittAndScarper Server Application.");
		
		System.out.printf("\n\t alone. Non-network mode is stated. Which mean both a HMI and a database is initialized.");
			
		System.out.printf("\n\n If no argument is specified a Client mode with a GUI is started. " +
				"The Client communicates through a RMI connection to the running Server application.\n");
		
		
	}
	
	/**
	 * Main entrance for the BodgittAndScarpert Application. 
	 * 
	 * @param args Following args are valid: server and alone. If args is not defined, client mode is selected.
	 */
	public static void main(String[] args) {	
		ModeFlag modeFlag = ModeFlag.CLIENT;
		
		//ignore other than first element in args array
		if (args != null && args.length > 0) {
			String mode = args[0];
			if (ModeFlag.SERVER.toString().equalsIgnoreCase(mode.trim())) {
				modeFlag = ModeFlag.SERVER;
			}
			else if (ModeFlag.ALONE.toString().equalsIgnoreCase(mode.trim())) {
				modeFlag = ModeFlag.ALONE;
			}
			else {
				showHelp(args[0]);
				System.exit(-1);
			}
			
			new Start(modeFlag);
		}
		else {
			//if no args specified start client
			new Start(modeFlag);
		}
			
	}

}
